<?php

namespace App\Http\Controllers;

use App\Jobs\ComposerUpdate;
use App\Jobs\GitUpdate;
use App\Jobs\NpmUpdate;
use App\Jobs\Production;
use Illuminate\Http\Request;


class SystemController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Show the application dashboard.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {

        $branchName = "develop/master"; //分支名，只对此分支进行更新

        $data = $request->all();

        // \Log::debug($data['ref']);
        // 1、 不是当前的分支，退出
        if (!isset($data['ref']) || $data['ref'] != "refs/heads/" . $branchName) {
            return $this->result(false);
        }

        $changeFiles = [];
        foreach ($data['commits'] as $commits) {
            $changeFiles = array_merge($changeFiles, $commits['added']);
            $changeFiles = array_merge($changeFiles, $commits['modified']);
            $changeFiles = array_merge($changeFiles, $commits['removed']);
        }
        $changeFiles = array_unique($changeFiles);
        sort($changeFiles);

        GitUpdate::dispatch($branchName);

        $fileName = "composer.json";
        if (in_array($fileName, $changeFiles)) {
            ComposerUpdate::dispatch();
        }

        // 4. 判断 是否更新 package.json
        $fileName = "package.json";
        if (in_array($fileName, $changeFiles)) {
            NpmUpdate::dispatch();
        }

        $isUpdate = false;


        $fileName = "resources";
        foreach ($changeFiles as $fileItem) {
            if (strstr($fileItem, $fileName)) {
                $isUpdate = true;
            }

        }

        if ($isUpdate) {
            Production::dispatch();
        }
    }
}
